package org.example.project.bookstore.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.bean.Alipay;
import org.example.bean.RocketMQOrder;
import org.springframework.stereotype.Component;

/**
 * @Auther:Liu
 * @Testname:OrderFailRefundAmountLinstener
 * @Date:2025/8/27 10:08
 */
@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "order_fail_2",topic = "order",selectorExpression = "error",messageModel = MessageModel.BROADCASTING)
public class OrderFailRefundAmountLinstener implements RocketMQListener<String> {
    @SneakyThrows
    public void onMessage(String s) {
        log.info("开始执行失败操作,开始退款");
        RocketMQOrder rocketMQOrder = JSON.parseObject(s, RocketMQOrder.class);
        log.info("rocketMQOrder数据为:{}",rocketMQOrder);
        AlipayClient client = rocketMQOrder.getAlipayClient();
        Alipay alipay = new Alipay();
        alipay.setOut_trade_no(rocketMQOrder.getOrderId());
        alipay.setRefund_amount(rocketMQOrder.getTotalPrice());
        log.info("开始执行退款操作：{}", alipay);
        // 产生退款对象
        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
        String json = JSONArray.toJSONString(alipay);
        refundRequest.setBizContent(json);
        AlipayTradeRefundResponse refundResponse = client.execute(refundRequest);
        if (refundResponse.isSuccess()) {
          log.info("退款成功");
        }
        log.info("退款失败");
    }
}
